package com.xyh.concurrency.example.deadLock;

import lombok.extern.slf4j.Slf4j;

/**
 * 简单的死锁
 * 解释明天解释
 */
@Slf4j
public class DeadLock implements Runnable {
    public int flag = 1;
    private static Object o1 = new Object(), o2 = new Object();

    @Override
    public void run() {
        log.info("flag:{}", flag);
        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    log.info("1");
                }
            }

        }
        if (flag == 2) {
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    log.info("0");
                }
            }

        }
    }

    public static void main(String[] args) {
        DeadLock deadLock = new DeadLock();
        DeadLock deadLock1 = new DeadLock();
        deadLock.flag = 1;
        deadLock1.flag = 0;
        /**
         *  因为这样出现了互斥条件 a 获得b 但是线程被别的线程锁定 b 想获得a 被别的线程锁定
         *  就会出现相互等待的情况
         *
         */
        new Thread(deadLock).start();
        new Thread(deadLock1).start();

    }
}
